package com.github.thinwonton.activemq.showcase.ack.mode.transacted;

import com.github.thinwonton.activemq.showcase.ActiveMQManager;

import javax.jms.*;
import java.io.IOException;

public class Consumer {


    public static void main(String[] args) throws IOException {
        try {
            Connection connection = ActiveMQManager.createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue(Utils.QUEUE_NAME);
            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try {
                        System.out.println("-------- ----- --------- ");
                        System.out.println("触发消息接收");
                        TextMessage textMessage = (TextMessage) message;
                        String text = textMessage.getText();
                        handleMsg(text);

                        System.out.println("成功处理消息 : " + text);
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }

                }
            });

            // 线程一直等待
            System.in.read();

            consumer.close();
            session.close();
            connection.stop();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void handleMsg(String msg) {
        System.out.println("准备处理消息 : " + msg);
        try {
            Thread.sleep(500);  //500毫秒处理一个
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //模拟处理的时候发生了异常
//        throw new RuntimeException("未知错误");
    }
}
